//
//  BuyMusicDetailViewViewController.m
//  MIDI
//
//  Created by E.M.Game on 15/9/10.
//  Copyright (c) 2015年 QXSX. All rights reserved.
//

#import "BuyMusicDetailViewViewController.h"
#import "AppConfig.h"
#import "UIViewController+NavItem.h"
#import "UIViewController+Create.h"
#import "UIImageView+AFNetworking.h"
#import "TMCache.h"
#import "UIImageView+WebCache.h"
#import "buyMusicDetailCell.h"
#import "APIAdress.h"
#import "MusicTexbookDetailModel.h"
#import "QXNetWorkTool.h"
#import "CommFunc.h"
#import "MBProgressHUD+YC.h"
#import "MusicTextBookOrderModel.h"
#import "UserDataSingleton.h"
#import "MyOrderPayViewControl.h"
#import "SIAlertView.h"
#import "OperanViewController.h"
#import "AliPayTool.h"
#import "AccountTool.h"
#import "WeChatPayTool.h"
#import "WXPrePayIdModel.h"
#import "WXApi.h"
#import <AlipaySDK/AlipaySDK.h>
#import "BuyMusicViewController.h"
#import "MyOrderViewController.h"

@interface BuyMusicDetailViewViewController ()<UITableViewDataSource , UITableViewDelegate , QXNetWorkToolDelegate , UIAlertViewDelegate , MyOrderPayViewDeletage>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;

@property(copy , nonatomic) NSString * pageTitle;
@property(strong , nonatomic) MusicTexbookDetailModel * data; //曲谱教程的详细数据
@property(strong , nonatomic) MusicTextBookOrderModel * orderData; //订单数据
@property(copy , nonatomic) NSString *materalId; //曲谱教程ID
@property(assign , nonatomic) BOOL isShowAddOrderBtn;
@property(assign , nonatomic) int payType;
@property(strong , nonatomic) buyMusicDetailCell * myCell;

@end

@implementation BuyMusicDetailViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.isShowAddOrderBtn = YES;
    
    self.payType = -1;
    
    [AccountTool savePayItem:VPayFail];
    [AccountTool savePayMusicPopToView:VPayBuyMusicPopToNone];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self configNavigationItem];
    [self refreshPage];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(void) configNavigationItem
{
    [self.navigationController.navigationBar setBarTintColor:MIDIColorOfNavigationBar];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    if(self.pageTitle == nil)
        self.pageTitle = @"曲谱购买";
    self.navigationItem.title = self.pageTitle;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],UITextAttributeFont,nil]];
    
    [self configNavigationBackAction:^{
        
        [self.navigationController popViewControllerAnimated:YES];
    }];    
}

#pragma mark tableView datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.data == nil)
        return 602;
    NSInteger res = 386 + 221 - 36 ;
    CGFloat width = [UIScreen mainScreen].bounds.size.width - 70;
    CGFloat maxHeight = 999;
    UIFont *font = [UIFont fontWithName:@"Hiragino Sans GB" size:12];
    NSString *str = self.data.introduction;
    CGSize maxSize = CGSizeMake(width, maxHeight);
    CGSize textSize = [CommFunc sizeWithString:str font:font max:maxSize];
    res = res + textSize.height;
    if(res < 602)
        res = 602;
    return res;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.myCell = [buyMusicDetailCell loadFromXib];
    [self configCell:self.myCell];
    return self.myCell;
}

#pragma mark - Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}


-(void) setData:(BOOL) isMusicPage data:(id)mydata Buy:(NSString *)buy
{
    if(isMusicPage)
        self.pageTitle = @"曲谱购买";
    else
        self.pageTitle = @"教程购买";
    self.materalId = mydata;
    self.buy = buy;
}

-(void)configCell : (buyMusicDetailCell*)cell
{
    if(self.data == nil)
        return;
    
    if (self.data && cell)
    {
        cell.contentView.hidden = NO;
    }
    
    cell.priceLb.hidden = YES;
    cell.itemTitleLb.hidden = YES;
    cell.descLb.hidden = YES;

    [cell.buyBtn addTarget:self action:@selector(pressBuyBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    [cell.joinOrderBtn addTarget:self action:@selector(pressJoinOrderBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    [cell.seeDetailBtn addTarget:self action:@selector(seeDetailBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    [cell.buySolidBtn addTarget:self action:@selector(pressBuySolidBtn:) forControlEvents:UIControlEventTouchUpInside];

    NSString * item = self.data.cover_img;
    NSURL * url = [NSURL URLWithString:item];
    [cell.myImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"img_buymusicdetail_loading"]];
    
    
    //加入3d效果
    cell.myImageView.layer.shadowColor = [UIColor grayColor].CGColor;//阴影颜色
    cell.myImageView.layer.shadowOffset = CGSizeMake(4, 4);//偏移距离
    cell.myImageView.layer.shadowOpacity = 0.5;//不透明度
    cell.myImageView.layer.shadowRadius = 2.0;//半径
    
    [cell.priceLb setText:[NSString stringWithFormat:@"%@" , self.data.price]];
    [cell.itemTitleLb setText:self.data.name];
    cell.priceLb.hidden = NO;
    cell.itemTitleLb.hidden = NO;
    cell.descLb.hidden = NO;
    [cell.descLb setText:self.data.introduction];
    
    cell.joinOrderBtn.hidden = YES;
    cell.buyBtn.hidden = YES;
    cell.seeDetailBtn.hidden = YES;
    cell.buySolidBtn.hidden = YES;
    
    if ([self.buy isEqualToString:@"0"]) //未购买
    {
        cell.joinOrderBtn.hidden = NO;
        cell.buyBtn.hidden = NO;
        cell.buySolidBtn.hidden = NO;
    }
    else
    {
        cell.seeDetailBtn.hidden = NO;
    }
}

-(void)pressJoinOrderBtn : (UIButton *)sender
{
    [self reqJoinOrder];
}

-(void)pressBuyBtn : (UIButton *)sender
{
    MusicTexbookDetailModel *itemdata = self.data;
    MyOrderPayViewControl *obj = [MyOrderPayViewControl create];
    obj.view.backgroundColor = [UIColor clearColor];
    obj.bgImage.alpha = 1;
    UIView *subView = [obj.view viewWithTag:999];
    subView.backgroundColor = [UIColor clearColor];
    
    obj.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    obj.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    obj.definesPresentationContext = YES;
    obj.myOrderPayViewDeletage = self;
    
    [obj setTitleData:itemdata.name];
    [self presentViewController:obj animated:YES completion:nil];
}

-(void)pressBuySolidBtn : (UIButton *)sender
{
    NSURL *detailUrl = [NSURL URLWithString:@"http://b.mashort.cn/h.6AOHN?sm=9a3102"];
    UIViewController * vc = [[UIViewController alloc]init];
    UIWebView *webView = [[UIWebView alloc]initWithFrame:self.parentViewController.view.bounds];
    NSURLRequest *req = [NSURLRequest requestWithURL:detailUrl];
    [webView loadRequest:req];
    [vc.view addSubview:webView];
    [self.navigationController pushViewController:vc animated:YES];
    [vc configNavigationBackAction:^{
        [vc.navigationController popViewControllerAnimated:YES];
    }];
}

-(void)seeDetailBtn : (UIButton *)sender
{
    OperanViewController * ctr = [OperanViewController create];
    [ctr setPDFData:self.data.file_url];
    [self.navigationController pushViewController:ctr animated:YES];
}

#pragma mark -----------MyOrderPayViewDeletage--------
-(void)pay:(int)type
{
    if (type == 1) //微信
    {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"确认支付" message:nil
                                                            delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
        
        alertView.tag = 111;
        
        [alertView show];
    }
    else if (type == 2) //支付宝
    {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"确认支付" message:nil
                                                            delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
        
        alertView.tag = 222;
        
        [alertView show];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 111)
    {
        //微信支付
        if (buttonIndex == 1)
        {
            self.payType = 0;
            [self WXPay];
            return;
        }
    }
    else if (alertView.tag == 222)
    {
        //支付宝支付
        if (buttonIndex == 1)
        {
            self.payType = 1;
            [self Alipay];
            return;
        }
    }
    else if (alertView.tag == 333)
    {
        //没有装微信
        return;
    }
    else if (alertView.tag == 444)
    {
        //查看详情
        
        if (buttonIndex == 1)
        {
            OperanViewController * ctr = [OperanViewController create];
            [ctr setPDFData:self.data.file_url];
            [self.navigationController pushViewController:ctr animated:YES];
        }
        
        return;
    }
}

-(void) WXPay
{
    if(![WXApi isWXAppInstalled]) // 判断 用户是否安装微信
    {
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:@"您未安装微信，请安装后付款。"
                                  message:nil
                                  delegate:self
                                  cancelButtonTitle:@"确定"
                                  otherButtonTitles:nil, nil];
        
        alertView.tag = 333;
        [alertView show];
        return;
    }
    
    [self createOrder];
}

-(void) Alipay
{
    [self createOrder];
}


-(void) collect
{
    //生成订单
    if(self.data == nil)
    {
        return;
    }
    
    UserDataSingleton *userData = [UserDataSingleton shareInstance];
    if(![userData isLogin])
    {
        [userData pleaseLogin:self];
        return;
    }
    
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    
    QXNetWorkTool *netTools = [[QXNetWorkTool alloc]init];
    netTools.QXNetWorkDelegate = self;
    
    [netTools GetDataFromServerWithPostMethodandInterfaceName:MusicTexBookCollectionInterface andParameter:@[@{@"material_id":self.data.id , @"user_id":userData.user_id , @"type":self.data.type, @"price":self.data.price}] tag:4];
}

-(void) createOrder
{
    //生成订单
    if(self.data == nil)
    {
        return;
    }
    
    UserDataSingleton *userData = [UserDataSingleton shareInstance];
    if(![userData isLogin])
    {
        [userData pleaseLogin:self];
        return;
    }
    
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    
    QXNetWorkTool *netTools = [[QXNetWorkTool alloc]init];
    netTools.QXNetWorkDelegate = self;
    
    [netTools GetDataFromServerWithPostMethodandInterfaceName:MusicTexBookOrderInterface andParameter:@[@{@"material_id":self.data.id , @"user_id":userData.user_id , @"type":self.data.type, @"price":self.data.price}] tag:2];
}


-(void) refreshPage
{
    if(self.materalId != nil)
    {
        [MBProgressHUD showMessage:@"正在加载" toView:self.view];
        
        QXNetWorkTool *netTools = [[QXNetWorkTool alloc]init];
        netTools.QXNetWorkDelegate = self;
        
        [netTools GetDataFromServerWithPostMethodandInterfaceName:MusicTexBookDetailInterface andParameter:@[@{@"material_id":self.materalId}] tag:1];
    }
}

-(void)reqJoinOrder
{
    [self collect];
}


#pragma    ---QuxNetTool
-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    if (tag == 1)
    {
        for(NSDictionary * dic in Response)
        {
            MusicTexbookDetailModel * item = [MusicTexbookDetailModel MyModelWithDict:dic];
            self.data = item;

            [AccountTool saveOrderId:item.id]; //曲谱教材id
            
            break;
        }
        
        [self.myTableView reloadData];
        return;
    }
    
    if(tag == 2)
    {
        //生成订单
        for(NSDictionary * dic in Response)
        {
            MusicTextBookOrderModel * item = [MusicTextBookOrderModel MyModelWithDict:dic];
            self.orderData = item;
            
            [AccountTool saveOrderId:item.order_id];
            
            break;
        }
        
        if (self.payType == 0)
        {
            QXNetWorkTool *netTools = [[QXNetWorkTool alloc]init];
            netTools.QXNetWorkDelegate = self;
            
            //微信支付
            int wxPrice = [self.data.price floatValue] * 100;
            NSString *strPrice = [[NSString alloc] initWithFormat:@"%d", wxPrice];
            
            //获得prepayid和noncestr
            [netTools GetDataFromServerWithPostMethodandInterfaceName:WXPayGetPrepayIdInterface andParameter:
             @[@{
                   @"totalfee":strPrice,
                   @"body":self.data.name,
                   @"outtradeno":self.orderData.order_code
                   }] tag:3];
        }
        else if (self.payType == 1)
        {
            [AccountTool savePayItem:VPayBuyMusic];
            
            //支付宝支付
            [AliPayTool alipayWithOrdercode:@"" orderId:self.orderData.order_id Price:self.data.price CityId:@"" Target:self];
        }
        
        self.payType = -1;
        
        return;
    }

    if(tag == 3)
    {
        for(NSDictionary * dic in Response)
        {
            WXPrePayIdModel * item = [WXPrePayIdModel WXPrePayIdModelWithDict:dic];
            
            NSString *prepayid = item.prepayid;
            NSString *noncestr = item.noncestr;
            
            int wxPrice = [self.data.price floatValue] * 100;
            NSString *strPrice = [[NSString alloc] initWithFormat:@"%d", wxPrice];
            
            [AccountTool savePayItem:VPayBuyMusic];
            
            //微信支付
            [WeChatPayTool WeChatWithOrdercode:@""
                                      prepayid:prepayid
                                       orderId:self.orderData.order_id
                                        Price :strPrice
                                        CityId:@""
                                      noncestr:noncestr
                                        Target:self];
            break;
        }
        
        return;
    }
    
    if(tag == 4)
    {
        //生成订单
        for(NSDictionary * dic in Response)
        {
            MusicTextBookOrderModel * item = [MusicTextBookOrderModel MyModelWithDict:dic];
            self.orderData = item;
            
            [AccountTool saveOrderId:item.order_id];
            
            break;
        }
        return;
    }
}

-(void)GetFailResponse:(id)Response andTag:(int)tag
{
    switch (tag)
    {
        case 6666:
        case 7777:
        case 8888:
            [MBProgressHUD hideHUD];
            //            [MBProgressHUD showSuccess:(NSString*)message];
            break;
        default:
        {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:(NSString*)Response toView:self.view];
            break;
        }
    }
}

-(void)GetSuccessMessage:(id)message andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    switch (tag)
    {
        case 2:
        case 4:
            [MBProgressHUD showSuccess:(NSString*)message];
            break;
            
        case 6666:
        {
            [MBProgressHUD hideHUD];
            
            if([[AccountTool takePayResult] isEqualToString:VPaySuccess])
            {
                self.buy = @"1";
                
                if (self.myCell)
                {
                    self.myCell.joinOrderBtn.hidden = YES;
                    self.myCell.buyBtn.hidden = YES;
                    self.myCell.seeDetailBtn.hidden = NO;
                }
                
                UIAlertView * alertView = [[UIAlertView alloc]
                                           initWithTitle:@"支付成功"
                                           message:nil
                                           delegate:self
                                           cancelButtonTitle:@"取消"
                                           otherButtonTitles:@"查看",nil];
                alertView.tag = 444;
                [alertView show];
            }
            
//            if( [[AccountTool takePayResult] isEqualToString:VPaySuccess])
//            {
//                if ([[AccountTool takePayMusicPopToView] isEqualToString:VPayBuyMusicPopToBuyMusicView])
//                {
//                    for (UIViewController *controller in self.navigationController.viewControllers)
//                    {
//                        if ([controller isKindOfClass:[BuyMusicViewController class]])
//                        {
//                            UIAlertView * alertView = [[UIAlertView alloc]
//                                                       initWithTitle:@"支付成功"
//                                                       message:nil
//                                                       delegate:(BuyMusicViewController*)controller
//                                                       cancelButtonTitle:@"查看"
//                                                       otherButtonTitles:@"取消",nil];
//                            alertView.tag = 444;
//                            [alertView show];
//                            break;
//                        }
//                    }
//                }
//                [self.navigationController popViewControllerAnimated:YES];
//            }
            break;
        }
//        case 7777:
//        case 8888:
//            [MBProgressHUD hideHUD];
//            [self.navigationController popViewControllerAnimated:YES];
//            break;
    }
}


@end



















